package conf

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"
)

var configValue = make(map[string]map[string]any)

func init() {
	var err error
	f, err := os.OpenFile("conf.json", os.O_RDONLY, os.ModePerm)
	if err != nil {
		fmt.Println("未加载到指定的配置文件,将读取系统默认配置,可通过首页进行修改")
	} else {
		defer f.Close()
		b, err := io.ReadAll(f)
		if err != nil {
			panic(fmt.Sprintf("初始化配置失败:%s", err.Error()))
		}
		ConfigValueJson = string(b)

	}
	if ConfigValueJson != "" {
		err = json.Unmarshal([]byte(ConfigValueJson), &configValue)
		if err != nil {
			fmt.Printf("初始化配置失败,走默认配置:%s\r\n", err.Error())
		}
	}
}

func GetConf(section string, key string) any {
	if configValue != nil {
		s, ok := configValue[section]
		if ok {
			k, ok := s[key]
			if ok {
				return k
			}
		}
	}
	return ""
}

func InitConfigJson(value string) (string, error) {
	ConfigValueJson = value
	f, err := os.OpenFile("conf.json", os.O_RDWR|os.O_TRUNC|os.O_CREATE, os.ModePerm)
	if err != nil {
		return ConfigValueJson, err
	}
	defer f.Close()
	err = f.Truncate(0)
	if err != nil {
		return value, err
	}
	_, err = f.Seek(0, 0)
	if err != nil {
		return value, err
	}
	_, err = fmt.Fprint(f, ConfigValueJson)
	if err != nil {
		return value, err
	}
	err = json.Unmarshal([]byte(ConfigValueJson), &configValue)
	if err != nil {
		panic(fmt.Sprintf("写入配置到内存失败:%s", err.Error()))
	}
	return ConfigValueJson, nil
}

func GetConfigJson() string {
	return ConfigValueJson
}

func SetConf(section string, key string, value any) (string, error) {
	if configValue != nil {
		s, ok := configValue[section]
		if !ok {
			return "", fmt.Errorf("不存在key:%s", section)
		}
		s[key] = value
		b, err := json.Marshal(configValue)
		if err != nil {
			return "", err
		}
		var out bytes.Buffer
		err = json.Indent(&out, b, "", "\t")
		if err != nil {
			return "", err
		}
		ConfigValueJson = out.String()
		if ConfigValueJson != "" {
			f, err := os.OpenFile("conf.json", os.O_RDWR|os.O_TRUNC|os.O_CREATE, os.ModePerm)
			if err != nil {
				return ConfigValueJson, err
			}
			f.Truncate(0)
			f.Seek(0, 0)
			fmt.Fprint(f, ConfigValueJson)
			return ConfigValueJson, nil
		}
	}
	return "", fmt.Errorf("配置没有初始化")
}

func GetConfKeys(section string) []string {
	if configValue != nil {
		s, ok := configValue[section]
		if ok {
			keys := make([]string, 0, len(s))
			for k := range s {
				keys = append(keys, k)
			}
			return keys
		}
	}
	return []string{}
}
